package com.example.javamaday.list;

import java.util.Stack;

/**
 * 逆波兰表达式
 */
public class EvalRPNTest {

    public static void main(String[] args) {
        String[] tokens = {"81"};
        int result = evalRPN(tokens);
        System.out.println("Result = " + result);
    }

    public static boolean isNumeric(String str) {
        try {
            Integer.valueOf(str);
        } catch (Exception e) {
            System.out.println(str + "is not number");
            return false;
        }
        return true;
    }

    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            if (isNumeric(tokens[i])) {
                stack.push(Integer.valueOf(tokens[i]));
                if (i == tokens.length - 1) {
                    return stack.pop();
                }
            } else {
                int first = stack.pop();
                int second = stack.pop();
                int result = 0;
                switch (tokens[i]) {
                    case "+":
                        result = second + first;
                        break;
                    case "-":
                        result = second - first;
                        break;
                    case "*":
                        result = second * first;
                        break;
                    case "/":
                        result = second / first;
                        break;
                }
                if (i == tokens.length - 1) {
                    return result;
                } else {
                    stack.push(result);
                    System.out.println("stack push result = " + result);
                }
            }
        }
        return 0;
    }
}
